#include "seqstack.h"


void SeqStackInit(SeqStack* s){
    if(s == NULL){
        return;
    }
    s->size = 0;
    s->capacity = 1000;
    s->data = (SeqStackType*)malloc(s->capacity*sizeof(SeqStackType));
}


void SeqStackResize(SeqStack* s){
    if(s == NULL){
        return;
    }
    if(s->size<s->capacity){
        return;
    }
    SeqStackType* new_data = (SeqStackType*)malloc(s->capacity*sizeof(SeqStackType)*2+1);
    size_t i = 0;
    for(;i<s->capacity;++i){
        new_data[i] = s->data[i];
    }
    s->data = new_data;
    return;
}

void SeqStackPush(SeqStack* s,SeqStackType value){
    if(s == NULL){
        return;
    }
    if(s->size >= s->capacity){
        SeqStackResize(s);
    }
    s->data[s->size++] = value;
    return;
}

void SeqStackPop(SeqStack* s){
    if(s == NULL){
        return;
    }
    if(s->size == 0){
        return;
    }
    --s->size;
}

int SeqStackTop(SeqStack* s,SeqStackType* value){
    if(s == NULL || value == NULL){
        return 0;
    }
    if(s->size == 0){
        return 0;
    }
    *value = s->data[s->size-1];
    return 1;
}

void SeqStackDestroy(SeqStack* s){
    if(s == NULL){
        return;
    }
    free(s->data);
    s->size = 0;
    s->capacity = 0;
    return;
}

//////////////////////////////////////////////////////////////////////////////////////
//                  以下为测试代码
/////////////////////////////////////////////////////////////////////////////////////

#if 0
#define TEST_HEADER printf("\n=========================%s=======================\n",__FUNCTION__)

void PrintfStack(SeqStack* s){
    if(s == NULL){
        return;
    }
    if(s->size == 0){
        return;
    }
    size_t i = 0;
    for(;i<s->size;++i){
        printf("[%c] ",s->data[i]);
    }
    printf("\n");
    return;
}

void test(){
    TEST_HEADER;
    SeqStack s;
    SeqStackInit(&s);
    SeqStackPush(&s,'a');
    SeqStackPush(&s,'b');
    SeqStackPush(&s,'c');
    SeqStackPush(&s,'d');
    PrintfStack(&s);


    SeqStackPop(&s);
    PrintfStack(&s);

    SeqStackType value;
    int ret = SeqStackTop(&s,&value);
    printf("ret expect 1,actual %d\n",ret);
    printf("value expect c,actual [%c]\n",value);

    SeqStackPop(&s);
    PrintfStack(&s);

    SeqStackPop(&s);
    PrintfStack(&s);

    SeqStackPop(&s);
    PrintfStack(&s);

    SeqStackPop(&s);
    PrintfStack(&s);
}


int main(){
    test();
    return 0;
} 
#endif
